package main
import (

	"net/http"
	"time"
	"strconv"
)

const (
	HOWMANY   = 18
	BASE_URL  = "http://new.southtv.cn:9180/"
	CDN_URL   = ""
)

func timeshiftHandler(w http.ResponseWriter, req *http.Request) {
	gid := req.FormValue("gid")
	start := req.FormValue("start")
	uuid := req.FormValue("uuid")

	if len(gid) < 2 || len(start) < 5 || len(uuid) < 5 {
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	t, err := strconv.ParseInt(start, 10, 64)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	now := time.Now().Unix()
	//timeshift cant less than 30 seconds
	if now <= (30 + t) {
		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
		w.Header().Set("Location", BASE_URL+gid+"/live.m3u8")
		w.WriteHeader(http.StatusFound)
		return
	}
	buf := GetM3u8(gid, t, uuid, CDN_URL)
	if len(buf) > 0 {
		w.Header().Set("Content-Type", "application/vnd.apple.mpegurl; charset=utf-8")
		w.WriteHeader(http.StatusOK)
		l, _ := w.Write(buf)
		_ = l
	} else {
		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
		w.Header().Set("Location", BASE_URL+gid+"/live.m3u8")
		w.WriteHeader(http.StatusFound)
		return
	}
	return
}

func StartPvr(work_dir string) {
	TimeshiftInit()
	http.HandleFunc("/pvr", timeshiftHandler)
        http.Handle("/", http.FileServer(http.Dir(work_dir)))
	logger.Fatal(http.ListenAndServe(":9999", nil))
}
